<template>
  <div>
    <!-- 1.0 头部导航结构 -->
    <van-nav-bar
      title="我的收藏"
      left-arrow
      @click-left="$router.back()"
      @click-right="$router.push({ path: '/' })"
    >
      <template #right>
        <van-icon
          name="wap-home-o"
          color="#f00"
          size="6vw"
        />
      </template>
    </van-nav-bar>
    <!-- 2.0 收藏列表 -->
    <div class="list">
      <van-swipe-cell
        v-for="item in starList"
        :key="item.id"
      >
        <MyPost :post="item"></MyPost>
        <template #right>
          <van-button
            square
            type="danger"
            text="删除"
            class="delete-btn"
            @click="deleteFn(item.id)"
          />
        </template>
      </van-swipe-cell>
    </div>
    <!-- 如果列表为空 - 展示空状态 -->
    <van-empty v-if="!starList.length" description="空空如也" />
  </div>
</template>

<script>
import { updatePostStarByIdAPI } from "../apis/news";
import { getUserStarAPI } from "../apis/user";
import MyPost from "../components/MyPost.vue";
export default {
  components: {
    MyPost,
  },
  data() {
    return {
      starList: [],
    };
  },
  async created() {
    const res = await getUserStarAPI();
    // console.log(res);
    this.starList = res.data.data.map((item) => {
      return {
        ...item,
        // 由于我的收藏页和首页评论的字段名不一样，需要我们自己处理
        comment_length: item.comments.length,
      };
    });
  },
  methods: {
    // 删除收藏文章
    deleteFn(id) {
      // console.log(id);
      // 弹窗确认
      this.$dialog
        .confirm({
          title: "是否真的删除？",
        })
        .then(async () => {
          // 用户点击了确定
          //  1. 界面展示 - 删除DOM节点
          this.starList = this.starList.filter((item) => item.id !== id);
          //  2. 请求发送 - 后端删除
          const res = await updatePostStarByIdAPI(id);
          // console.log(res);
          this.$toast.success(res.data.message);
        })
        .catch(() => {});
    },
  },
};
</script>

<style lang="less" scoped>
.delete-btn {
  height: 100%;
}
</style>